package com.joyintech.filter;

import com.joyintech.util.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class TraceIdFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String traceId = httpRequest.getHeader("X-Trace-Id"); // 从HTTP头中获取traceId，或者生成一个新的
        if (traceId == null || traceId.isEmpty()) {
            traceId = IDGenerator.generate(20); // 如果没有提供，生成一个UUID作为traceId
        }
        log.info("接口请求链路的日志->{}",traceId);
        MDC.put("traceId", traceId); // 将traceId放入MDC
        ((HttpServletResponse) response).setHeader("X-Trace-Id", traceId);
        try {
            chain.doFilter(request, response); // 继续执行过滤器链
        } finally {
            MDC.remove("traceId"); // 请求处理完毕后移除traceId，避免内存泄漏
        }
    }
}
